import { createStore } from 'vuex'
import axios from 'axios'
import userApi from '../api/user'

export default createStore({
    state: {
        token: localStorage.getItem('token') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
        userType: localStorage.getItem('userType') || '', // '管理员' 或 '物业员工'
        employeeType: localStorage.getItem('employeeType') || null
    },
    getters: {
        isAuthenticated(state) {
            return !!state.token
        },
        isAdmin(state) {
            return state.userType === '管理员'
        },
        isStaff(state) {
            return state.userType === '物业员工'
        }
    },
    mutations: {
        setToken(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
        },
        setUserType(state, userType) {
            state.userType = userType
            localStorage.setItem('userType', userType)
        },
        setEmployeeType(state, employeeType) {
            state.employeeType = employeeType
            if (employeeType) {
                localStorage.setItem('employeeType', employeeType)
            } else {
                localStorage.removeItem('employeeType')
            }
        },
        clearAuth(state) {
            state.token = ''
            state.userInfo = {}
            state.userType = ''
            state.employeeType = null
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('userType')
            localStorage.removeItem('employeeType')
        }
    },
    actions: {
        // 登录动作
        async login({ commit }, { phone, password, userType }) {
            try {
                const response = await userApi.login(phone, password, userType)

                // 检查响应格式
                if (response.data) {
                    // 提取token和用户信息，适配不同的响应格式
                    const { access, refresh, token, userId, userName, email, employeeType } = response.data

                    // 按优先级选择token: access > refresh > token
                    const authToken = access || refresh || token

                    if (authToken) {
                        // 调试信息
                        console.log('登录成功，获取到token:', authToken)
                        console.log('员工类型:', employeeType)

                        commit('setToken', authToken)
                        const userInfo = {
                            phone, // phone从请求参数中获取
                            userId: userId || response.data.user_id,
                            userName: userName || response.data.username,
                            email,
                            employeeType
                        }
                        commit('setUserInfo', userInfo)
                        commit('setUserType', userType)
                        commit('setEmployeeType', employeeType) // 单独设置员工类型
                        return Promise.resolve(response.data)
                    } else {
                        return Promise.reject(new Error('未获取到有效的认证令牌'))
                    }
                } else {
                    return Promise.reject(new Error('登录响应格式错误'))
                }
            } catch (error) {
                console.error('登录失败:', error)
                return Promise.reject(error)
            }
        },

        // 登出动作
        logout({ commit }) {
            commit('clearAuth')
        }
    }
}) 